<template>
  <view class="question-container">
    <!-- 顶部信息栏 -->
    <view class="question-header">
      <!-- 左侧：题号 + 徽章 -->
      <view class="left-group">
        <text class="question-index">第{{ currentQuestion + 1 }}题</text>
        <nut-avatar class="type-badge" shape="round" bg-color="#f90"
          style="width: 60px; height: 30px; font-size: 14px; color: #fff;">
          {{ questionTypeText }}
        </nut-avatar>
      </view>

      <!-- 右侧：图标组 -->
      <view class="right-group">
        <IconFont class="icon" name="setting" size="32" @click="showSettings" />
        <IconFont class="icon" name="ask" size="32" @click="showFeedbackModal" />
      </view>
    </view>
    <!-- 题目内容 -->
    <view class="question-content">
      <view class="question-title">{{ questionData.title }}</view>
    </view>
    <!-- 单选 -->
    <nut-radio-group v-model="selectedOption" v-if="questionData.type === 1" appearance="none">
      <nut-cell v-for="(option, index) in questionData.options" :key="index" class="option-item" :class="{
        active: selectedOption === option.value,
        correct: isCorrect === '1' && option.value === questionData.correctAnswer,
        wrong:
          isCorrect === '-1' && option.value !== questionData.correctAnswer &&
          selectedOption === option.value
      }" @click="onClickOption(option.value)">
        <nut-radio :label="option.value" class="full-width-radio" appearance="none">
          <text class="option-key">{{ getOptionLabel(index) }}</text>
          <text class="option-text">{{ option.label }}</text>
        </nut-radio>
      </nut-cell>
    </nut-radio-group>

    <!-- 多选 已经用 @click 手动控制了 selectedOption.value，不需要再使用 NutUI 的 v-model-->
    <nut-checkbox-group v-if="questionData.type === 2" appearance="none">
      <nut-cell v-for="(option, index) in questionData.options" :key="index" class="option-item" :class="{
        active: selectedOption.includes(option.value),
        correct:
          isCorrect === '1' && questionData.correctAnswer.includes(option.value) &&
          selectedOption.includes(option.value),
        wrong:
          isCorrect === '-1' &&

          selectedOption.includes(option.value)
      }" @click="onClickOption(option.value)">
        <nut-checkbox :label="option.value" class="full-width-checkbox">
          <text class="option-key">{{ getOptionLabel(index) }}</text>
          <text class="option-text">{{ option.label }}</text>
        </nut-checkbox>
      </nut-cell>
    </nut-checkbox-group>

    <!-- 判断题 -->
    <nut-radio-group v-model="selectedOption" v-if="questionData.type === 3" appearance="none">
      <nut-cell v-for="(option, index) in questionData.options.slice(0, 2)" :key="index" class="option-item" :class="{
        active: selectedOption === option.value,
        correct:
          isCorrect === '1' && option.value === questionData.correctAnswer,
        wrong:
          isCorrect === '-1' &&
          option.value !== questionData.correctAnswer &&
          selectedOption === option.value
      }" @click="onClickOption(option.value)">
        <nut-radio :label="option.value" class="full-width-radio" appearance="none">
          <text class="option-key">{{ getOptionLabel(index) }}</text>
          <text class="option-text">{{ option.label }}</text>
        </nut-radio>
      </nut-cell>
    </nut-radio-group>

    <!-- 选项 -->
    <!-- <view class="options-container">
      <nut-radio-group v-model="selectedOption">
        <nut-cell v-for="(option, index) in questionData.options" :key="index" class="option-item">
          <nut-radio :label="option.key">{{ option.value }}</nut-radio>
        </nut-cell>
      </nut-radio-group>
    </view> -->
    <!-- 确认按钮 -->
    <view class="confirm-btn">
      <nut-button type="info" block @click="confirmAnswer">确认</nut-button>
    </view>
    <!-- 解析内容 -->
    <view v-if="showAnalysisContent" class="analysis-content">
      <view class="analysis-title">题目解析</view>
      <view class="analysis-answer">正确答案：{{ answerText }}</view>
      <view class="analysis-text" v-html="questionData.analysis"></view>
    </view>
  </view>
  <!-- 设置弹窗 -->
  <nut-popup v-model:visible="showSettingModal" position="bottom" :style="{ height: '40%' }">
    <view class="popup-content">
      <nut-cell v-for="(cell, index) in settingCells" :key="index" :title="cell.title" :desc="cell.desc"
        @click="showPicker(index)" />
    </view>

    <!-- 动态显示对应的 picker -->
    <view v-if="currentPickerIndex !== null" class="picker-container">
      <nut-picker :columns="settingCells[currentPickerIndex].arrays" :title="settingCells[currentPickerIndex].title"
        @confirm="handleConfirm" @cancel="hidePicker" />
    </view>
  </nut-popup>

  <!-- 问题反馈弹窗 -->
  <nut-popup v-model:visible="showFeedback" position="bottom" :style="{ height: '50%' }">
    <view class="feedback-container">
      <!-- 标题栏：问题反馈 + 关闭按钮 -->
      <view class="feedback-header">
        <text class="title">问题反馈</text>
        <IconFont name="close" size="20" @click="cancelFeedBack" />
      </view>

      <!-- 输入区域 -->
      <textarea class="feedback-input" v-model="feedbackContent" placeholder="请输入问题反馈，字数限制200字" :maxlength="200"
        auto-height></textarea>

      <!-- 字数统计 -->
      <view class="word-count">{{ feedbackContent.length }}/200</view>

      <!-- 按钮区域：一行两个按钮 -->
      <view class="feedback-actions">
        <nut-button type="default" block @click="cancelFeedBack">取消</nut-button>
        <nut-button type="info" block @click="submitFeedback">确认</nut-button>
      </view>
    </view>
  </nut-popup>

  <!-- 选择字体大小 -->
  <!-- <nut-picker v-model="val" :columns="columns" :title="String(val)" @confirm="confirm" /> -->
  <!-- <view v-if="showSettingModal" class="setting-modal" :class="{ 'show': showSettingModal }">
      <view class="modal-header">
        <text>设置</text>
        <IconFont name="close" size="20" @click="hideSettings" />
      </view>

      <view class="setting-item">
        <text>字体大小</text>
        <nut-picker :columns="fontSizeOptions" :model-value="selectedFontSize" @change="onFontSizeChange">
          <nut-button plain type="primary" block shape="round">{{ selectedFontSizeLabel }}</nut-button>
        </nut-picker>
      </view>

      <view class="setting-item">
        <text>自动跳转下一题</text>
        <nut-switch v-model="autoNextEnabled" @change="onAutoNextChange" />
      </view>
    </view> -->
  <!-- 答题卡弹窗 -->
  <view v-show="showAnswerSheetModal" class="answer-sheet-modal" :class="{ 'show': showAnswerSheetModal }">
    <view class="sheet-header">
      <text>答题卡</text>
      <IconFont name="close" size="30" @click="hideAnswerSheet" />
    </view>
    <view class="sheet-body">
      <view v-for="(item, index) in questionList" :key="index" class="question-circle" :class="{
        current: index === currentQuestion,
        answered: isQuestionAnswered(index),
        correct: isQuestionCorrect(index) === 1,
        wrong: isQuestionCorrect(index) === 0
      }" @click="goToQuestion(index)">
        {{ index + 1 }}
      </view>
    </view>
  </view>
  <!-- 底部导航 -->
  <view class="bottom-nav">
    <nut-button plain type="info" size="small" @click="prevQuestion">上一题</nut-button>
    <IconFont name="star-fill" size="32" :style="{ color: isCollected ? '#FFD700' : '#ddd' }" @click="toggleCollect" />
    <nut-button plain type="info" size="small" @click="showAnswerSheet">答题卡</nut-button>
    <nut-button plain type="info" size="small" @click="showAnalysis">解析</nut-button>
    <nut-button plain type="info" size="small" @click="nextQuestion">下一题</nut-button>
  </view>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import Taro from '@tarojs/taro'
import { IconFont } from '@nutui/icons-vue'
import config from '../../config'

// 当前题目索引
const currentQuestion = ref(0)
// 是否收藏
const isCollected = ref(false)
// 选择的答案
const selectedOption = ref([])
// 题目数据列表
const questionList = ref([])
// 当前题目对象
const questionData = ref({
  id: null,
  type: 1, // 题型：1-单选 2-多选 3-判断
  title: '',
  options: [], // 解析后的选项
  correctAnswer: '',
  analysis: ''
})
// 题目选项类型判断集合
const questionTypeText = computed(() => {
  switch (questionData.value.type) {
    case 1:
      return '单选题'
    case 2:
      return '多选题'
    case 3:
      return '判断题'
    default:
      return '未知题型'
  }
})
//答案文本
const answerText = ref('');
// 获取页面参数
const query = ref('')
//禁用标记，当选出正确答案，禁用选项
const disableFlag = ref(false)
//用于改变背景色
const isCorrect = ref('0') // 0 表示未提交，true=1，false=-1
//用于控制解析
const showAnalysisContent = ref(false)
//用于控制答题卡
const showAnswerSheetModal = ref(false)
//用于答题记录集合
const answerRecordList = ref([])
//设置弹窗
const showSettingModal = ref(false)
const selectedFontSize = ref(['medium']) // 默认值：'large', 'medium', 'small'
const selectedFontSizeLabel = ref('中')
const autoNextEnabled = ref(false) // 默认开启自动跳转
// 当前选中的 picker 索引
const currentPickerIndex = ref(null);
// picker 的选中值
const selectedPickerValue = ref('');
// 字体大小选项
const fontSizeOptions = [
  { text: '大', value: 'large', index: 0 },
  { text: '中', value: 'medium', index: 1 },
  { text: '小', value: 'small', index: 2 }
]
const columns = [
  {
    text: '是',
    value: true
  },
  {
    text: '否',
    value: false
  }
]
//设置弹窗的表格cell内容
const settingCells = [
  {
    title: '调整字体大小',
    desc: '中',
    arrays: fontSizeOptions

  },
  {
    title: '是否自动切换下一题',
    desc: '否',
    arrays: columns
  }
]
//保存反馈的json格式
const feedbackData = ref({
  userId: null,
  questionId: null,
  content: '',
  handleContent: 0,
  createTime: ''
});
//收藏对象
const collectData = ref({
  userId: null,
  questionId: null,
  createTime: '',
  delFlag: null
});
//收藏集合（）
const collectList = ref([]);
// 控制反馈弹窗显示
const showFeedback = ref(false);
// 反馈内容
const feedbackContent = ref('');

// 显示反馈弹窗
const showFeedbackModal = () => {
  showFeedback.value = true;
};
//  取消反馈
const cancelFeedBack = () => {
  feedbackContent.value = '';
  showFeedback.value = false;
};
// 提交反馈
const submitFeedback = async () => {
  if (feedbackContent.value.trim() === '') {
    Taro.showToast({ title: '反馈内容不能为空', icon: 'none' });
    return;
  }

  // 这里可以调用 API 提交反馈内容
  try {
    const wxRequest = config.wxPromisify(wx.request);
    feedbackData.value = {
      //Taro.getStorageSync('userId')
      userId: 1,
      questionId: questionData.value.id,
      content: feedbackContent.value,
      handleContent: 0,
      createTime: formatTime(new Date())
    };

    // let rowData = {
    //   //Taro.getStorageSync('userId')
    //   userId: 1,
    //   questionId: questionData.value.id,
    //   content: feedbackContent.value,
    //   handleContent: 0,
    //   createTime: formatTime(new Date())
    // };
    const res = await wxRequest({
      url: `${config.apiUrl}/feedback/save`,
      method: 'POST',
      header: { 'Content-Type': 'application/json' },
      data: feedbackData.value
    })

    // const res = Taro.request({
    //   url: `${config.apiUrl}/feedback/save`,
    //   method: 'POST',
    //   header: { 'content-type': 'application/json' },
    //   data: feedbackData.value
    // })
    // if (res.data.code === '0') {
    //   Taro.showToast({ title: '保存成功', icon: 'success' })
    // } else {
    //   Taro.showToast({ title: '保存失败', icon: 'none' })
    // }


    // 清空内容并关闭弹窗
    feedbackContent.value = '';
    showFeedback.value = false;
  } catch (err) {
    console.error('请求失败:', err);
    Taro.showToast({ title: '网络错误', icon: 'none' });
  }

  // 清空内容并关闭弹窗
  feedbackContent.value = '';
  showFeedback.value = false;
};
// 显示指定的 picker
const showPicker = (index) => {
  currentPickerIndex.value = index;
  selectedPickerValue.value = settingCells[index]?.desc || '';
};

// 隐藏 picker
const hidePicker = () => {
  currentPickerIndex.value = null;
};
// 显示设置弹窗
const showSettings = () => {
  showSettingModal.value = true
}
const handleConfirm = (value, index) => {
  console.log("value1", value)
  if (currentPickerIndex.value !== null) {
    const selectedItem = settingCells[currentPickerIndex.value];
    console.log("select", selectedItem)
    if (selectedItem) {
      // 更新 desc 字段
      console.log("selectedItem", value.selectedOptions)
      selectedItem.desc = value.selectedOptions[0].text;

      // 根据不同的 cell 做不同处理
      switch (currentPickerIndex.value) {
        case 0: // 字体大小
          onFontSizeChange(value.selectedOptions[0].index, value.selectedOptions[0].index);
          break;
        case 1: // 是否自动跳转
          onAutoNextChange(value.selectedOptions[0].value);
          break;
        default:
          console.log('未知设置项');
      }

      hidePicker(); // 关闭 picker
    }
  }
};
// 隐藏设置弹窗
const hideSettings = () => {
  showSettingModal.value = false
}

// 字体大小变化处理
const onFontSizeChange = (value, index) => {
  const option = fontSizeOptions[index]
  console.log("option", option)
  selectedFontSize.value = [option.value] // 保持数组格式
  selectedFontSizeLabel.value = option.text

  // 更新全局样式类（用于动态调整题目字体）
  document.body.className = `font-size-${option.value}`
}

// 自动跳转开关变化
const onAutoNextChange = (val) => {
  autoNextEnabled.value = val
}

onMounted(() => {
  const params = Taro.getCurrentInstance().router.params
  if (params?.id) {
    query.value = params.id
    fetchQuestions()
  }
})

onUnmounted(() => {
  // 页面卸载前执行
  handleExit()
})

// 处理用户退出页面逻辑
const handleExit = async () => {
  await submitAllRecords()
  // Taro.reLaunch({ url: '/pages/index/index' }) // 强制跳转首页
}
// 生成 A/B/C/D 字母标签
const getOptionLabel = (index) => {
  return String.fromCharCode(65 + index) // 0 -> A, 1 -> B...
}
// 获取题目数据
const fetchQuestions = async () => {
  try {
    const wxRequest = config.wxPromisify(wx.request)
    const res = await wxRequest({
      url: `${config.apiUrl}/question/findOfId/${query.value}`,
      method: 'GET',
      header: { 'content-type': 'application/json' }
    })

    const resCllotion = await wxRequest({
      url: `${config.apiUrl}/collection/find/${1}`,
      method: 'GET',
      header: { 'content-type': 'application/json' }
    })

    console.log('接口返回:', res.data)

    if (res.data.code === '0') {
      questionList.value = res.data.data || []
      collectList.value = resCllotion.data.data || []
      updateQuestionData()
      isQuestionCollected(questionData.value.id)
    } else {
      Taro.showToast({ title: '获取题目失败', icon: 'none' })
    }

  } catch (err) {
    console.error('请求失败:', err)
    Taro.showToast({ title: '网络错误', icon: 'none' })
  }
}
//表格的点击事件
const onClickOption = (val) => {
  console.log('点击了选项:', val)
  isCorrect.value = '0'
  if (questionData.value.type === 2) {
    // 多选题：确保是数组
    const arr = selectedOption.value || []

    const index = arr.indexOf(val)
    if (index > -1) {
      // 已存在则移除
      selectedOption.value = arr.filter(item => item !== val)
    } else {
      // 不存在则添加
      selectedOption.value = [...arr, val]
    }
  } else {
    // 单选/判断题
    selectedOption.value = val
  }
}
// 更新当前题目数据
const updateQuestionData = () => {
  if (questionList.value.length === 0) return

  const current = questionList.value[currentQuestion.value]

  // 查找答题记录
  const record = answerRecordList.value.find(r => r.questionId === current.id)

  questionData.value = {
    id: current.id,
    type: current.type,
    title: current.questionText,
    options: JSON.parse(current.answerOptions),
    correctAnswer: formatCorrectAnswer(current.correctAnswer),
    analysis: current.answerAnalysis,
    userAnswer: record ? record.userAnswer : null
  }

  // 根据题型初始化 selectedOption
  if (current.type === 2) {
    // 多选题
    selectedOption.value = record && record.userAnswer ? [...record.userAnswer] : []
  } else {
    // 单选/判断题
    selectedOption.value = record ? record.userAnswer : ''
  }

  // 设置是否正确状态
  if (record) {
    isCorrect.value = record.correct === 1 ? '1' : '-1'
  } else {
    isCorrect.value = '0'
  }
}
// 上一题，重置选项isCorrect，避免直接出答案
const prevQuestion = () => {
  showAnalysisContent.value = false;
  if (currentQuestion.value > 0) {
    currentQuestion.value--
    updateQuestionData();
    isQuestionCollected(questionData.value.id);
  }
}

// 下一题.重置选项isCorrect，避免直接出答案
const nextQuestion = () => {
  showAnalysisContent.value = false;
  if (currentQuestion.value < questionList.value.length - 1) {
    currentQuestion.value++
    updateQuestionData()
    console.log("questionData:", questionData.value.id);
    isQuestionCollected(questionData.value.id);
  } else {
    // 已是最后一题，弹窗确认是否提交
    Taro.showModal({
      title: '提示',
      content: '您已完成全部题目，是否提交？',
      success: async (res) => {
        if (res.confirm) {
          await submitAllRecords()
          // Taro.reLaunch({ url: '/pages/index/index' }) // 跳转到首页
        }
      }
    })
  }
}

// 将正确答案统一转为字符串格式（如 ["A","B"] → "AB"）
const formatCorrectAnswer = (answer) => {
  if (!answer) return ''
  if (Array.isArray(answer)) {
    // 如果是数组，去重后排序并拼接成字符串
    return [...new Set(answer)].sort().join('')
  } else if (typeof answer === 'string') {
    // 如果是字符串，去除非字母字符后排序
    return answer.replace(/[^A-Z]/g, '').split('').sort().join('')
  }

  return ''
}
// 格式化答案为字符串存储（数组 → 字符串）
const formatAnswerForSave = (answer) => {
  if (!answer) return ''
  if (Array.isArray(answer)) {
    return answer.join('')
  }
  return answer
}
// 格式化时间为 "YYYY-MM-DD HH:mm"
const formatTime = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从 0 开始
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}`
}
//保存答题记录
const saveAnswerRecord = (status) => {
  const current = questionList.value[currentQuestion.value]
  const userId = Taro.getStorageSync('userId') || 1 // 示例：从本地缓存获取用户ID
  const questionId = current.id
  const userAnswer = selectedOption.value
  let correct = 2 // 默认为无答案
  console.log("提交答案", isCorrect.value)
  if (status === 'submit') {
    if (isCorrect.value === '1') {
      console.log('提交答案1');
      correct = 1
    } else if (isCorrect.value === '-1') {
      console.log('提交答案-1');
      correct = 0
    }
  }
  const record = {
    userId,
    questionId,
    userAnswer: formatAnswerForSave(userAnswer),
    correct,
    updateTime: formatTime(new Date())
  }
  // 更新或新增记录
  const existingIndex = answerRecordList.value.findIndex(r => r.questionId === questionId)
  if (existingIndex > -1) {
    // 已存在则更新
    answerRecordList.value.splice(existingIndex, 1, record)
  } else {
    // 否则添加
    answerRecordList.value.push(record)
  }
  // // 同步更新 questionList 中的 userAnswer（用于答题卡判断）
  // questionList.value[currentQuestion.value].userAnswer = userAnswer
}
//确认答案
const confirmAnswer = () => {
  const correct = questionData.value.correctAnswer
  const userAnswer = selectedOption.value

  if (questionData.value.type === 2) {
    // 多选题：排序后转字符串比对
    const correctArray = correct.split(',').filter(Boolean)
    const userArray = selectedOption.value || []

    const correctSorted = correctArray.sort().join('')
    const userSorted = userArray.sort().join('')
    console.log('用户答案排序后:', userSorted);
    console.log('正确答案排序后:', correctSorted);
    if (userSorted === correctSorted) {
      isCorrect.value = '1'
      disableFlag.value = true
      Taro.showToast({ title: '回答正确!', icon: 'success' })
    } else {
      isCorrect.value = '-1'
      Taro.showToast({ title: '回答错误!', icon: 'none' })
    }
  } else {
    // 单选或判断题
    if (userAnswer === correct) {
      isCorrect.value = '1'
      disableFlag.value = true
      Taro.showToast({ title: '回答正确!', icon: 'success' })
    } else {
      isCorrect.value = '-1'
      Taro.showToast({ title: '回答错误!', icon: 'none' })
    }
  }

  // 提交后保存记录
  saveAnswerRecord('submit');
  // 如果启用自动跳转且不是最后一题
  if (autoNextEnabled.value && currentQuestion.value < questionList.value.length - 1) {
    setTimeout(() => {
      nextQuestion()
    }, 500)
  }
}
// 提交所有记录到后端
const submitAllRecords = async () => {
  try {
    const wxRequest = config.wxPromisify(wx.request)
    console.log('answerRecordList', answerRecordList.value)
    const res = await wxRequest({
      url: `${config.apiUrl}/userAnswer/addAll`,
      method: 'POST',
      header: { 'content-type': 'application/json' },
      data: answerRecordList.value
    })
    const resCllotion = await wxRequest({
      url: `${config.apiUrl}/collection/save`,
      method: 'POST',
      header: { 'content-type': 'application/json' },
      data: collectList.value
    })
    if (res.data.code === '0' && resCllotion.data.code === '0') {
      Taro.showToast({ title: res.data.msg, icon: 'success' })
    } else {
      Taro.showToast({ title: res.data.msg, icon: 'none' })
    }
  } catch (err) {
    console.error('提交失败:', err)
    Taro.showToast({ title: '网络错误', icon: 'none' })
  }
}
// 显示解析
const showAnalysis = () => {
  //用于答案的处理，使点击解析时，能出现答案
  answerText.value = formatCorrectAnswer(questionData.value.correctAnswer);
  showAnalysisContent.value = !showAnalysisContent.value
}

// 收藏切换
const toggleCollect = () => {
  isCollected.value = !isCollected.value
  let questionId = questionData.value.id;
  if (isCollected.value) {
    // 收藏
    collectData.value = {
      userId: 1,
      questionId: questionId,
      createTime: formatTime(new Date()),
      delFlag: 0
    }
    collectList.value.push(collectData.value)
  } else {
    // 取消收藏
    const index = collectList.value.findIndex(item => item.questionId === questionId)
    if (index > -1) {
      collectList.value[index].delFlag = 1
    }
  }
  console.log('收藏列表', collectList.value)
  Taro.showToast({
    title: isCollected.value ? '已收藏' : '已取消收藏',
    icon: 'none'
  })

}
//判断是否收藏
function isQuestionCollected(questionId) {
  console.log('判断是否收藏id', questionId);
  const existingIndex = collectList.value.findIndex(item => item.questionId === questionId);
  if(existingIndex > -1){
    
  }
  isCollected.value = (existingIndex > -1);
  console.log('判断是否收藏', isCollected.value);
}
// 判断是否已回答
const isQuestionAnswered = (index) => {
  const questionId = questionList.value[index]?.id;
  const existingIndex = answerRecordList.value.findIndex(r => r.questionId === questionId);
  if (existingIndex === -1) {
    return false;
  }
  // console.log('判断是否已回答:', answerRecordList)
  // console.log('判断是否已回答correct:', answerRecordList.value[index].correct)
  // console.log('判断是否已回答answerRecordList[index]:', answerRecordList[index])
  // console.log('判断是否已回答answerRecordList.value[index]:', answerRecordList.value[index])
  const q = answerRecordList.value[existingIndex]?.correct
  return q !== 2
}

// 判断是否正确
const isQuestionCorrect = (index) => {
  const questionId = questionList.value[index]?.id;
  const existingIndex = answerRecordList.value.findIndex(r => r.questionId === questionId);
  if (existingIndex === -1) {
    return 2;
  }
  const q = answerRecordList.value[existingIndex]?.correct
  console.log("记录对象判断答题卡是否正确：", q)
  return q

  // const correct = formatCorrectAnswer(q.correctAnswer)
  // const user = formatCorrectAnswer(q.userAnswer)
}

// 显示答题卡
// const showAnswerSheet = () => {
//   Taro.showToast({ title: '点击了答题卡' })
//   console.log('显示答题卡')
//   showAnswerSheetModal.value = true
// }

function showAnswerSheet() {
  showAnswerSheetModal.value = true
}

// 隐藏答题卡
const hideAnswerSheet = () => {
  showAnswerSheetModal.value = false
}

// 跳转到指定题目
const goToQuestion = (index) => {
  // 先保存当前题的答题记录
  // console.log('index', answerRecordList)
  currentQuestion.value = index
  updateQuestionData()
  isQuestionCollected(questionData.value.id)
  hideAnswerSheet()
}

</script>

<style lang="scss">
.question-container {
  padding: 20px;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

// 问题头部
.question-header {
  display: flex;
  align-items: center;
  justify-content: space-between; // 左右对齐
  margin-bottom: 15px;

  .left-group {
    display: flex;
    align-items: center;
    gap: 8px; // 第X题 和 徽章之间的间距
  }

  .question-index {
    font-size: 30px;
    font-weight: bold;
  }

  .type-badge {
    width: 60px;
    height: 30px;
    background-color: #ff9900; // 橘黄色
    color: #fff; // 白色文字
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%; // 保持圆形/椭圆
  }

  .right-group {
    display: flex;
    align-items: center;
    gap: 12px; // 图标之间留出间距
  }

  .icon {
    width: 32px;
    height: 32px;
  }
}

// 问题内容样式
.question-content {
  margin-bottom: 20px;

  .question-title {
    font-size: 30px;
    line-height: 1.5;
  }
}

.options-container {
  flex: 1;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background-color: #f9f9f9;
  transition: background-color 0.3s;

  &.active {
    background-color: #4ea8ec; // 蓝色背景
    color: white;
  }

  &.correct {
    background-color: #72e23a; // 绿色 - 正确答案
    color: white;
  }

  &.wrong {
    background-color: #ee4043; // 红色 - 用户答错的选项
    color: white;
  }

  .full-width-radio {
    flex: 1;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    font-size: 16px;
    background-color: transparent;

    .nut-radio__icon {
      display: none !important; //关键：隐藏默认圆点
    }

    .nut-radio__label {
      padding-left: 0 !important; // 去掉 label 前的空白
    }
  }

  //所选样式
  .full-width-checkbox {
    flex: 1;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    font-size: 16px;
    background-color: transparent;

    .nut-checkbox__icon {
      display: none !important;
    }

    .nut-checkbox__label {
      padding-left: 0 !important;
    }
  }

  .option-key {
    display: inline-block;
    width: 30px;
    height: 30px;
    text-align: center;
    line-height: 24px;
    border-radius: 4px;
    margin-right: 10px;
    font-weight: bold;
    // background-color: #e0e0e0;
    color: #333;
  }

  .option-text {

    flex: 1;
    color: inherit;
  }
}

.confirm-btn {
  margin: 20px 0;
}

.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px 0;
  background-color: #fff;
  z-index: 999;
  display: flex;
  justify-content: space-around;
  align-items: center;
  box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.1); // 可选：加个阴影提升层级感
}

//解析的样式
.analysis-content {
  margin-top: 20px;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 8px;
  font-size: 14px;
  color: #333;
  line-height: 1.6;
}

.analysis-title {
  font-weight: bold;
  margin-bottom: 10px;
  font-size: 32px;
  color: #2b9cf2;
}

.analysis-answer {
  white-space: pre-wrap; // 保留换行和空格
  font-size: 32px;
  font-weight: bold;
}

.analysis-text {
  white-space: pre-wrap; // 保留换行和空格
  font-size: 32px;
}

.analysis-text p {
  margin-bottom: 10px;
}

.analysis-text strong {
  color: #ff4d4f;
  font-weight: bold;
}

//答题卡样式
.answer-sheet-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;

  .sheet-header {
    background-color: #fff;
    padding: 16px;
    font-size: 18px;
    font-weight: bold;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #eee;
  }

  .sheet-body {
    display: flex;
    flex-wrap: wrap;
    background-color: #f8f8f8;
    padding: 20px;
    max-height: 400px;
    overflow-y: auto;
  }

  .question-circle {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background-color: #e0e0e0;
    color: #333;
    font-size: 30px;
    font-weight: bold;
    margin: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;

    &.current {
      background-color: #2b9cf2;
      color: white;
    }

    &.answered {
      background-color: #72e23a;
      color: white;
    }

    &.correct {
      background-color: #72e23a;
      color: white;
    }

    &.wrong {
      background-color: #ee4043;
      color: white;
    }
  }

  //设置图标所需的样式
  .setting-modal {
    position: fixed;
    top: 100%;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #fff;
    // z-index: 9999;
    padding: 20px;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    transform: translateY(-100%);
    transition: transform 0.3s ease-in-out;
    // z-index: 99999;

    &.show {
      transform: translateY(0);
    }

    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 20px;
    }

    .setting-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 25px;
    }
  }

  //反馈样式
  .feedback-container {
    padding: 20px;
    background-color: #f9f9f9;

    .feedback-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      .title {
        font-size: 18px;
        font-weight: bold;
        color: #333;
      }

      .nut-icon {
        color: #999;
        cursor: pointer;
      }
    }

    .feedback-input {
      width: 100%;
      min-height: 120px;
      max-height: 200px;
      padding: 12px 16px;
      font-size: 16px;
      line-height: 1.5;
      color: #333;
      background-color: #fff;
      border: 1px solid #ddd;
      border-radius: 12px;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
      resize: none;
      outline: none;
      transition: border-color 0.3s ease;

      &::placeholder {
        color: #bbb;
        font-style: italic;
      }

      &:focus {
        border-color: #2b9cf2;
        box-shadow: 0 0 0 2px rgba(43, 156, 242, 0.2);
      }
    }

    .word-count {
      text-align: right;
      font-size: 12px;
      color: #999;
      margin-top: 8px;
      margin-bottom: 20px;
    }

    .feedback-actions {
      display: flex;
      gap: 12px;

      button {
        flex: 1;
        font-size: 16px;
        padding: 12px 0;
        border-radius: 8px;
      }

      .nut-button--default {
        background-color: #eee;
        color: #666;
      }

      .nut-button--info {
        background-color: #2b9cf2;
        color: #fff;
      }
    }
  }

  // .popup-content {
  //   padding-bottom: 60px;
  //   /* 留出空间给 picker */
  // }

  // .picker-container {
  //   position: absolute;
  //   bottom: 0;
  //   left: 0;
  //   right: 0;
  //   background-color: #fff;
  //   z-index: 10;
  // }
}
</style>